/**
 * 
 */
package com.swg.cocobox.message.internal;

import java.nio.charset.Charset;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import com.swg.cocobox.message.Message;
import com.swg.cocobox.message.MessageContext;

/**
 * @author satriaprayoga
 *
 */
public class UTFMessageParser implements MessageParser {

	static String regex="(\\G\\s*?\\{\\s*?(((origin|destination|content|mode){1}\\s*?:\\s*?([A-Za-z0-9\\s?*\\_\\@]*?){1}))\\s*?\\}\\s*?)\\1*?";
	static Pattern pattern=Pattern.compile(regex,Pattern.CASE_INSENSITIVE);
	
	@Override
	public Message parseMessage(byte[] data) {
		String input=new String(data, Charset.forName("UTF-8"));
		input=input.trim();
		Matcher matcher=pattern.matcher(input);
		String content=null;
		String origin=null;
		String dest=null;
		String mode=null;
		Message message=null;
		while(matcher.find()){
			if(matcher.group(4).equals("origin"))
				origin=matcher.group(5).trim();
			else if(matcher.group(4).equals("destination"))
				dest=matcher.group(5).trim();
			else if(matcher.group(4).equals("content"))
				content=matcher.group(5).trim();
			else if(matcher.group(4).equals("mode"))
				mode=matcher.group(5).trim();
		}

		if(mode.equalsIgnoreCase(MessageContext.PM)){
			message=new PrivateMessageImpl(origin, content, dest, Charset.forName("US-ASCII"));
		}else if(mode.equalsIgnoreCase(MessageContext.BR)){
			message=new BroadcastMessageImpl(origin, content, Charset.forName("US-ASCII"));
		}
		return message;
	}

}
